package com.bawei.module_mine.viewmodel

import androidx.lifecycle.viewModelScope
import com.bawei.lib_common.mvi.base.BaseViewModel
import com.bawei.module_mine.intent.AddAddressIntent
import com.bawei.module_mine.model.entity.AddAddressRequest
import com.bawei.module_mine.model.service.AddressService
import com.bawei.module_mine.state.AddAddressState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

class AddAddressViewModel : BaseViewModel<AddAddressIntent>() {
    private val _state = MutableStateFlow<AddAddressState>(AddAddressState.Init)
    val state: StateFlow<AddAddressState> get() = _state
    private val service by lazy { AddressService() }

    override fun handleIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect { intent ->
                when (intent) {
                    is AddAddressIntent.SaveAddress -> saveAddress(intent)
                }
            }
        }
    }

    private fun saveAddress(intent: AddAddressIntent.SaveAddress) {
        _state.value = AddAddressState.Loading
        viewModelScope.launch {
            try {
                val body = AddAddressRequest(
                    address = intent.address,
                    checked = false,
                    cityCode = intent.cityCode,
                    cityName = intent.city,
                    default = intent.isDefault,
                    districtCode = intent.districtCode,
                    districtName = intent.district,
                    postalCode = null,
                    provinceCode = intent.provinceCode,
                    provinceName = intent.province,
                    receiverName = intent.name,
                    receiverPhone = intent.phone
                )
                val result = service.addAddress(body)
                if (result.code == 200) {
                    _state.value = AddAddressState.Success
                } else {
                    _state.value = AddAddressState.Failed(result.msg ?: "保存失败")
                }
            } catch (e: Exception) {
                _state.value = AddAddressState.Failed(e.message ?: "网络异常")
            }
        }
    }
} 